package cvi.com.reader.activity;

import static android.content.Context.MODE_PRIVATE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.hawk.Hawk;

import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.audiorecord.MyHandler.MyHandler2;
import cvi.com.reader.audiorecord.interfaces.IAudioCallback;
import cvi.com.reader.audiorecord.interfaces.IPhoneState;
import cvi.com.reader.audiorecord.service.UploadingService;
import cvi.com.reader.audiorecord.utils.FileUtils;
import cvi.com.reader.audiorecord.utils.TimeUtil;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.HotBean;
import cvi.com.reader.bean.LoginBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.network.NetWorkManager2;
import cvi.com.reader.uploadrecord.ProgressListener;
import cvi.com.reader.uploadrecord.ProgressRequestBody;
import cvi.com.reader.voiceAssessment.Result;
import cvi.com.reader.voiceAssessment.xml.XmlResultParser;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by 梅涛 on 2020/8/5.
 * <p>
 * 作品详情页-汉语-朗读录音
 */

public class WorksDetailsAcitivity2 extends BaseActivity implements View.OnClickListener, IAudioCallback, IPhoneState {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tittle)
    TextView tittle;
    @BindView(R.id.right_icon)
    LinearLayout rightIcon;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.cc)
    ScrollView cc;
    @BindView(R.id.progressBar)
    SeekBar progressBar;
    @BindView(R.id.current_time)
    TextView currentTime;
    @BindView(R.id.all_time)
    TextView allTime;
    @BindView(R.id.play_btn)
    ImageView playBtn;
    @BindView(R.id.play_tv)
    TextView playTv;
    @BindView(R.id.play_btn_ll)
    LinearLayout playBtnLl;
    @BindView(R.id.restar_btn)
    ImageView restarBtn;
    @BindView(R.id.restar_tv)
    TextView restarTv;
    @BindView(R.id.bgm_btn)
    ImageView bgmBtn;
    @BindView(R.id.bgm_tv)
    TextView bgmTv;
    @BindView(R.id.bgm_btn_ll)
    LinearLayout bgmBtnLl;
    @BindView(R.id.finish_btn)
    ImageView finishBtn;
    @BindView(R.id.finish_tv)
    TextView finishTv;
    @BindView(R.id.finish_btn_ll)
    LinearLayout finishBtnLl;
    @BindView(R.id.about_begin)
    TextView aboutBegin;
    @BindView(R.id.about_begin_ll)
    RelativeLayout aboutBeginLl;
    @BindView(R.id.restar_btn_ll)
    LinearLayout restarBtnLl;
    @BindView(R.id.stop_recorder_btn)
    ImageView stopRecorderBtn;
    @BindView(R.id.stop_recorder_tv)
    TextView stopRecorderTv;
    @BindView(R.id.stop_recorder_ll)
    LinearLayout stopRecorderLl;
    @BindView(R.id.progressBar_ll)
    RelativeLayout progressBarLl;
    @BindView(R.id.loading_tv)
    TextView loadingTv;
    @BindView(R.id.large)
    ImageView large;
    @BindView(R.id.small)
    ImageView small;
    @BindView(R.id.floatin)
    ImageView floatin;
    private boolean  isSee=false;
    private int  size=17;
    private HotBean.RowsBean rowsBean = null;
    private int musicId = 1;
    private MediaPlayer mediaPlayer = new MediaPlayer();//实例化MediaPlayer类
    private String url = null;
    private TimerTaskChildren taskChildren;
    private Timer timer = new Timer();
    //数据倒计时3s
    private int countDown = 4;
    //总倒计时6s
    private int allCountDown = 6;
    //结束倒计时5秒钟
    private int endCountDown = 0;
    //录音状态1：开始录音，2：录音暂停，3：录音完成
    private int recordingStatus = 0;
    //录音开始倒计时界面不滑动
    private boolean isScroll = true;
    private DialogPlus recordStatusDialog;
    // private DialogPlus scoreDialog;//得分弹框
    //   private AudioRecorder audioRecorder;
    private boolean isKeepTime;//是否正在录音
    private AlertDialog upLoading;
    private AlertDialog scoreDialog;
    private AlertDialog musicDialog;
    /**
     * 支持定时和周期性执行的线程池
     */
    private ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
    private int time;
    private static final int INITIAL_DELAY = 0;
    private static final int PERIOD = 1000;
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    private List<String> mPermissionList = new ArrayList<>();
    private MyHandler2 myHandler = new MyHandler2(this);
    private final static int HANDLER_CODE = 0x0249;
    private boolean isDialogShow = true;
    private int scoreValue;//分值
    private LoginBean loginBean = null;//用户信息
    private String record_path;//绝对路径
    private boolean isAgain = false;//是否是第二次以上重新录制
    private int material_id = -10;
    private int user_id = -5;
    private String fileType;
    // 设置透明度渐变动画
    private AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);

    // 设置缩放渐变动画
    private ScaleAnimation scaleAnimation = new ScaleAnimation(0.5f, 2f, 0.5f, 2f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

    //科大讯飞---语音测评
    private SpeechEvaluator mIse;
    private final static String PREFER_NAME = "ise_settings";
    private final static int REQUEST_CODE_SETTINGS = 1;
    // 评测语种
    private String language;
    // 评测题型
    private String category;
    // 结果等级
    private String result_level;

    private String mLastResult;
    private String contentText;

    private float totalScore = 0;
    private int integrity_score;// 完整度分
    private int phone_score;// 声韵分
    private int tone_score;// 调型分
    private int fluency_score;// 流畅度分

    private boolean isCallback;
    private String fileTime;
    private boolean isRestart;//是否是重新录制，是则不弹框，不是则弹出分数弹框。
    private boolean isThereMusic;
    private String musicStr = "";
    private boolean isShowMusicDialog = true;
    private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
    private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
    private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
    private static final String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符
    // 评测监听接口
    private EvaluatorListener mEvaluatorListener = new EvaluatorListener() {

        @Override
        public void onResult(EvaluatorResult result, boolean isLast) {
            Log.d(TAG, "evaluator result :" + isLast);
            if (isLast) {
                StringBuilder builder = new StringBuilder();
                builder.append(result.getResultString());
                if (!TextUtils.isEmpty(builder)) {
                    // mResultEditText.setText(builder.toString());
                    mLastResult = builder.toString();
                    XmlResultParser resultParser = new XmlResultParser();
                    Result res = resultParser.parse(mLastResult);

                    if (null != res) {
                        // mResultEditText.setText(result.toString());
                        Log.d(TAG, result.toString() + "result11=" + res.total_score);
                        Log.d(TAG, "result11==" + res.total_score);
                        totalScore = res.total_score;
                        integrity_score = (int) res.integrity_score;
                        phone_score = (int) res.phone_score;
                        tone_score = (int) res.tone_score;
                        fluency_score = (int) res.fluency_score;
                        Log.d(TAG, "evaluator result :" + isLast + "   res====" + res.toString() + "totalScore=" + totalScore);
                        if (isRestart) {
                            return;
                        }
                        //分数返回时将计算分数加载界面隐藏。
                        progressBarLl.setVisibility(View.GONE);
                        playBtnLl.setEnabled(true);
                        playTv.setText("开始录音");
                        bgmBtnLl.setEnabled(true);
                        bgmBtnLl.setVisibility(View.GONE);
                        showScoreDialog();
                        record_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + FileUtils.rootPath + "/" + fileTime + ".wav";
                    }
                }
                //    mIseStartButton.setEnabled(true);
                //  showTip("评测结束");
            }
        }

        @Override
        public void onError(SpeechError error) {
            if (error != null) {
                //Toast.makeText(WorksDetailsAcitivity2.this, "error:" + error.getErrorCode() + "," + error.getErrorDescription(), Toast.LENGTH_SHORT).show();
              /*  mResultEditText.setText("");
                mResultEditText.setHint("请点击“开始评测”按钮");*/
                Log.d(TAG, error.getErrorCode() + "," + error.getErrorDescription());
                progressBarLl.setVisibility(View.GONE);
                playBtnLl.setEnabled(true);
                playTv.setText("开始录音");
                bgmBtnLl.setEnabled(true);
            } else {
                Log.d(TAG, "evaluator over");
            }
        }

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            Log.d(TAG, "evaluator begin");
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            Log.d(TAG, "evaluator stoped");
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            Log.d(TAG, "返回音频数据：" + data.length);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }

    };
    /**
     * 线程处理Handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case constant.WORKS_DETAIL_TIME:
                    isScroll = false;
                    String str = msg.getData().getString("countDown");//接受msg传递过来的参数
                    Log.d("asdad", str);
                    aboutBegin.setText(str);
                    if (allCountDown < 1) {
                        aboutBegin.startAnimation(scaleAnimation);
                        aboutBegin.startAnimation(alphaAnimation);
                    }
                    bgmBtnLl.setEnabled(false);
                    if (0 == allCountDown) {
                        restarBtnLl.setVisibility(View.VISIBLE);
                        aboutBeginLl.setVisibility(View.GONE);
                        bgmBtnLl.setVisibility(View.GONE);
                        bgmBtnLl.setEnabled(true);
                        stopRecorderLl.setVisibility(View.VISIBLE);
                        playBtn.setImageResource(R.mipmap.ic_audition_puase);
                        countDown = 4;
                        allCountDown = 6;
                        isDialogShow = false;
                        if (isAgain) {
                            if (url != null) {
                                // mediaPlayer.seekTo(0);
                                onPlayerClick(url);//---------------------//倒计时结束后重新播放音乐
                            }
                        } else {
                            if (mediaPlayer != null) {
                                if (-1 == musicId) {//取消音乐时开启录音时音乐不再播放，按钮显示“未选择配乐”
                                    onPauseClick();//停止从页面返回时的播放的音乐
                                } else {
                                    mediaPlayer.seekTo(0);

                                }

                            }
                        }


                        if (taskChildren != null) {
                            taskChildren.cancel();
                            isScroll = true;
                        }
                        /*
                         * 倒计时结束开始录音--代码
                         * */
                        try {

                            if (null == mIse) {
                                //  Toast.makeText(WorksDetailsAcitivity2.this, "创建对象失败，请确认 libmsc.so 放置正确，且有调用 createUtility 进行初始化", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if (mIse == null) {
                                return;
                            }
                            if (rowsBean.getContent() == null) {
                                return;
                            }
                            fileTime = String.valueOf(System.currentTimeMillis());
                            Log.d(TAG,stringFilter1(rowsBean.getContent())+"   == "+rowsBean.getContent());
                            CharSequence charSequence = Html.fromHtml(rowsBean.getContent());
                            contentText = charSequence.toString();
                            mLastResult = null;
                            setParams();
                            int ret = mIse.startEvaluating(stringFilter1(delHTMLTag(rowsBean.getContent())), null, mEvaluatorListener);
                            playBtn.setImageResource(R.mipmap.ic_recording);
                            playBtn.setEnabled(false);
                            playTv.setText("正在录音");
                            isKeepTime = true;
                            isRestart = false;
                         /*   if (audioRecorder.getStatus() == AudioStatus.STATUS_NO_READY) {
                                //初始化录音
                                String fileName = new SimpleDateFormat("yyyyMMddhhmmss", Locale.CHINA).format(new Date());
                                audioRecorder.createDefaultAudio(fileName);
                                audioRecorder.startRecord();
                                playBtn.setImageResource(R.mipmap.ic_audition_puase);
                                isKeepTime = true;
                                //  setClickable(true);
                            } else {
                                if (audioRecorder.getStatus() == AudioStatus.STATUS_START) {
                                    phoneToPause();
                                } else {
                                    audioRecorder.startRecord();
                                    playBtn.setImageResource(R.mipmap.ic_start_audiod);
                                    isKeepTime = true;

                                }
                            }*/
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        }

                        /*
                         * 倒计时结束开始录音--代码
                         * */
                    }

                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_works_details;
    }

    @Override
    protected void initView() {
        //设置动画持续时间
        alphaAnimation.setDuration(1000);
        scaleAnimation.setDuration(1000);
        back.setOnClickListener(this);
        bgmBtnLl.setOnClickListener(this);
        restarBtnLl.setOnClickListener(this);
        finishBtnLl.setOnClickListener(this);
        playBtnLl.setOnClickListener(this);
        stopRecorderLl.setOnClickListener(this);
        floatin.setOnClickListener(this);
        large.setOnClickListener(this);
        small.setOnClickListener(this);
        aboutBeginLl.getBackground().setAlpha(127);
        if (Hawk.contains("WorksDetails")) {
            rowsBean = Hawk.get("WorksDetails");
            material_id = rowsBean.getId();
            //统计朗读和浏览次数
            putClickNum(constant.WORKS_CLICK_NUM, material_id);
            tittle.setText("《" + rowsBean.getMaterial_name() + "》" + "-" + rowsBean.getAuthor());
            if ("1".equals(rowsBean.getCenter())) {
                content.setText(Html.fromHtml(rowsBean.getContent()));

            } else if ("0".equals(rowsBean.getCenter())) {
                content.setText("        " + Html.fromHtml(rowsBean.getContent()));

            } else {
                content.setText(Html.fromHtml(rowsBean.getContent()));
            }

        }

        if (Hawk.contains("size")){
            String s=Hawk.get("size");
            content.setTextSize(Float.valueOf(s));
        }



        progressBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.d("ACETEST", "监听");
                return true;
            }
        });
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                isAgain = true;
               /* mediaPlayer.reset();
                mediaPlayer.seekTo(0);*/
            }
        });
        mediaPlayer.setLooping(true);
        cc.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                if (!isScroll) {
                    return true;
                } else {
                    return false;
                }

            }
        });

        progressBar.setMax(5 * 60);
    }

    @Override
    protected void initData() {
        // audioRecorder = AudioRecorder.getInstance(this);
        scheduledThreadPool.scheduleAtFixedRate(() -> {
            if (isKeepTime) {
                ++time;
                if ((1000 * 60 * 5 - time * 1000) <= 5000) {
                    endCountDown++;
                    Log.d("endCountDown", endCountDown + "");
                }
                myHandler.sendEmptyMessage(HANDLER_CODE);
            }
        }, INITIAL_DELAY, PERIOD, TimeUnit.MILLISECONDS);

    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mIse = SpeechEvaluator.createEvaluator(WorksDetailsAcitivity2.this, null);
        setEvaText();
    }

    // 设置评测试题
    private void setEvaText() {
        SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
        language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn");
        category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence");

        String text = "";
        if ("en_us".equals(language)) {
            if ("read_word".equals(category)) {
                text = getString(R.string.text_en_word);
            } else if ("read_sentence".equals(category)) {
                text = getString(R.string.text_en_sentence);
            }
        } else {
            // 中文评测
            if ("read_syllable".equals(category)) {
                text = getString(R.string.text_cn_syllable);
            } else if ("read_word".equals(category)) {
                text = getString(R.string.text_cn_word);
            } else if ("read_sentence".equals(category)) {
                text = getString(R.string.text_cn_sentence);
            }
        }

        //  mEvaTextEditText.setText(text);
        //   mResultEditText.setText("");
        mLastResult = null;
        //mResultEditText.setHint("请点击“开始评测”按钮");
    }

    private void setParams() {
        SharedPreferences pref = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
        // 设置评测语言
        language = pref.getString(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置需要评测的类型
        category = pref.getString(SpeechConstant.ISE_CATEGORY, "read_sentence");
        // 设置结果等级（中文仅支持complete）
        result_level = pref.getString(SpeechConstant.RESULT_LEVEL, "complete");
        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        String vad_bos = pref.getString(SpeechConstant.VAD_BOS, "500000");
        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        String vad_eos = pref.getString(SpeechConstant.VAD_EOS, "180000");
        // 语音输入超时时间，即用户最多可以连续说多长时间；
        String speech_timeout = pref.getString(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");
        mIse.setParameter("rst", "entirety");
        mIse.setParameter("ise_unite", "1");
        mIse.setParameter("extra_ability", "multi_dimension");
        mIse.setParameter(SpeechConstant.LANGUAGE, language);
        mIse.setParameter(SpeechConstant.ISE_CATEGORY, category);
        mIse.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
        mIse.setParameter(SpeechConstant.VAD_BOS, vad_bos);
        mIse.setParameter(SpeechConstant.VAD_EOS, vad_eos);
        mIse.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, speech_timeout);
        mIse.setParameter(SpeechConstant.RESULT_LEVEL, result_level);
        mIse.setParameter(SpeechConstant.AUDIO_FORMAT_AUE, "opus");
        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mIse.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIse.setParameter(SpeechConstant.ISE_AUDIO_PATH, Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + FileUtils.rootPath + "/" + fileTime + ".wav");

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (constant.WORKS_DETAIL_CODE == requestCode) {
            isThereMusic = true;
            String musicName = data.getStringExtra("musicName");
            String author = data.getStringExtra("author");
            url = data.getStringExtra("url");
            musicId = data.getIntExtra("musicId", -1);
            bgmTv.setText(author + "-" + musicName);
            musicStr = author + "--" + musicName;
            onPlayerClick(url);
        /*    Uri uri = Uri.parse(url);//网络中的音乐文件
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(this, uri);//音乐文件路径
                mediaPlayer.prepare();//资源文件准备
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();//播放
                mediaPlayer.setLooping(true);
            }*/

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                //清除列表播放暂停标识
                finish();
                // jump(MainActivity2.class);
                break;
            case R.id.bgm_btn_ll:
                if (isThereMusic) {
                    showMusicDialog();
                } else {
                    Intent intent = new Intent(WorksDetailsAcitivity2.this, BackgroundMusicActivity.class);
                    startActivityForResult(intent, constant.WORKS_DETAIL_CODE);
                }
                break;
            case R.id.play_btn_ll:
                putClickNum(constant.READER_CLICK_NUM, material_id);
                if (isDialogShow) {
                    recordingStatus = 1;//开始录音标识
                    aboutBeginLl.setVisibility(View.VISIBLE);
                    taskChildren = new TimerTaskChildren("1");
                    timer.schedule(taskChildren, 0, 1000);
                    playBtn.setImageResource(R.mipmap.ic_audition_puase);
                    playTv.setText("正在录音");
                } else {
                    try {
                       /* if (audioRecorder.getStatus() == AudioStatus.STATUS_NO_READY) {
                            //初始化录音
                            String fileName = new SimpleDateFormat("yyyyMMddhhmmss", Locale.CHINA).format(new Date());
                            audioRecorder.createDefaultAudio(fileName);
                            audioRecorder.startRecord();
                            playBtn.setImageResource(R.mipmap.ic_audition_puase);
                            isKeepTime = true;
                            //  setClickable(true);
                        } else {
                            if (audioRecorder.getStatus() == AudioStatus.STATUS_START) {
                                phoneToPause();
                                if (url != null) {
                                    onPauseClick();//-----------------------------------------
                                }

                            } else {
                                audioRecorder.startRecord();
                                playBtn.setImageResource(R.mipmap.ic_audition_puase);
                                isKeepTime = true;
                                if (url != null) {
                                    onPlayerClick(url);//---------------------------------------
                                }

                            }
                        }*/
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    }
                }

                break;
            case R.id.stop_recorder_ll:
                showDialog("1");
                break;
            case R.id.restar_btn_ll:
                showDialog("3");
                break;

            case R.id.large:
                size++;
             content.setTextSize(Float.valueOf(size+""));
             Hawk.put("size",size+"");
                break;
            case R.id.small:
                size--;
                content.setTextSize(Float.valueOf(size+""));
                Hawk.put("size",size+"");
                break;
            case R.id.floatin:
               if (!isSee){
                   large.setVisibility(View.VISIBLE);
                   small.setVisibility(View.VISIBLE);
                   isSee=true;

               }else {
                   large.setVisibility(View.GONE);
                   small.setVisibility(View.GONE);
                   isSee=false;

               }

                break;


        }

    }

    /*
     *
     * 发布朗读作品/存入草稿箱
     * */
    private void sendData(int is_released) {
        progressBarLl.setVisibility(View.VISIBLE);
        progressBarLl.getBackground().setAlpha(125);
        loadingTv.setText("作品上传中...");
        back.setEnabled(false);
        bgmBtnLl.setEnabled(false);
        playBtnLl.setEnabled(false);
        File file = null; //生成文件
        //根据文件的后缀名，获得文件类型
        //  int 0->保存, 1->发布, 2->取消
        Map<String, Object> map = new HashMap<>();
        map.put("score", scoreValue);
        if (record_path != null) {
            file = new File(record_path);
            fileType = getMimeType(file.getName());
            if (Hawk.contains("LoginBean")) {
                loginBean = Hawk.get("LoginBean");
                user_id = loginBean.getData().getUser_info().getId();
            }
        }
        //把文件封装在RequestBody里
        RequestBody requestBody = RequestBody.create(MediaType.parse(fileType), file);
        ProgressRequestBody progressBody = new ProgressRequestBody(MediaType.parse(fileType), file, new ProgressListener() {
            @Override
            public void onProgress(long currentBytes, long contentLength, boolean done) {
                Log.e("chris", "currentBytes:" + currentBytes);
                Log.e("chris", "contentLength" + contentLength);
                Log.e("chris", (100 * currentBytes) / contentLength + " % done ");
                Log.e("chris", "done:" + done);
                Log.e("chris", "================================");
                //当前上传的进度值
            }
        });
        MultipartBody.Part part = MultipartBody.Part.createFormData("record", file.getName(), requestBody);
        if (-1 == musicId) {
            NetWorkManager2.getInstance().getNetWorkApiService().sendNoBgmData(constant.user_id, scoreValue, 0, integrity_score, phone_score, tone_score, fluency_score, 0, material_id, is_released, part).compose(this.<JSONObject>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<JSONObject>(WorksDetailsAcitivity2.this) {
                        @Override
                        protected void onFail(JSONObject response) {
                            super.onFail(response);
                            progressBarLl.setVisibility(View.GONE);
                            back.setEnabled(true);
                            bgmBtnLl.setEnabled(true);
                            playBtnLl.setEnabled(true);
                            Toast.makeText(WorksDetailsAcitivity2.this, "上传失败！", Toast.LENGTH_LONG).show();
                            Log.e("onFail111", "response=" + response.toString());
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            Log.e("onFail222", "response=" + e.getMessage());
                            progressBarLl.setVisibility(View.GONE);
                            back.setEnabled(true);
                            bgmBtnLl.setEnabled(true);
                            playBtnLl.setEnabled(true);
                            Toast.makeText(WorksDetailsAcitivity2.this, "上传失败！", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        protected void onSuccess(JSONObject response) {
                            progressBarLl.setVisibility(View.GONE);
                            back.setEnabled(true);
                            bgmBtnLl.setEnabled(true);
                            playBtnLl.setEnabled(true);
                            Toast.makeText(WorksDetailsAcitivity2.this, "上传成功！", Toast.LENGTH_LONG).show();
                        }
                    });
        } else {
            NetWorkManager2.getInstance().getNetWorkApiService().sendData(constant.user_id, scoreValue, 0, integrity_score, phone_score, tone_score, fluency_score, 0, material_id, is_released, musicId, part).compose(this.<JSONObject>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<JSONObject>(WorksDetailsAcitivity2.this) {
                        @Override
                        protected void onFail(JSONObject response) {
                            super.onFail(response);
                            progressBarLl.setVisibility(View.GONE);
                            back.setEnabled(true);
                            bgmBtnLl.setEnabled(true);
                            playBtnLl.setEnabled(true);
                            Toast.makeText(WorksDetailsAcitivity2.this, "上传失败！", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            progressBarLl.setVisibility(View.GONE);
                            back.setEnabled(true);
                            bgmBtnLl.setEnabled(true);
                            playBtnLl.setEnabled(true);
                            Toast.makeText(WorksDetailsAcitivity2.this, "上传失败！", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        protected void onSuccess(JSONObject response) {
                            progressBarLl.setVisibility(View.GONE);
                            back.setEnabled(true);
                            bgmBtnLl.setEnabled(true);
                            playBtnLl.setEnabled(true);
                            Toast.makeText(WorksDetailsAcitivity2.this, "上传成功！", Toast.LENGTH_LONG).show();
                        }
                    });
        }
    }

    private void finishAndReset() {
        isKeepTime = false;
        //audioRecorder.stopRecord();
        playBtn.setImageResource(R.mipmap.ic_start_audiod);
        time = 0;
        currentTime.setText("朗读已用时" + "00:00");
        if (mIse.isEvaluating()) {
            mIse.stopEvaluating();
            isKeepTime = false;
            progressBar.setProgress(0);
        }
        //setClickable(false);
    }

    @Override
    public void phone() {
       /* if (audioRecorder.getStatus() == AudioStatus.STATUS_START) {
            phoneToPause();
        }*/

    }

    /**
     * 暂停录音和状态修改
     */
    private void phoneToPause() {
        //    audioRecorder.pauseRecord();
        playBtn.setImageResource(R.mipmap.ic_start_audiod);
        isKeepTime = false;
        onPauseClick();//音乐随着暂停
    }

    @Override
    public void showPlay(String filePath) {
        File file = new File(filePath);
        record_path = filePath;
        Log.d("gfgfgijj", filePath);
        if (file.exists()) {
//            //合成完后的操作，根据需要去做处理，此处用于测试播放
//            audioRecorder.play(filePath);
            Intent intent = new Intent(this, UploadingService.class);
            intent.putExtra("test", "test");
            startService(intent);
        }

    }

    private void showDialog(final String flag) {
        //1;录制结束。2：是否发布作品.3:重新录制
        View view = LayoutInflater.from(WorksDetailsAcitivity2.this).inflate(R.layout.dialog_works_datail, null);
        Button confirm = view.findViewById(R.id.confir_btn);
        Button cancel = view.findViewById(R.id.cancel_btn);
        TextView stutasTv = view.findViewById(R.id.stutas_tv);
        TextView contentTv = view.findViewById(R.id.content_tv);
        if ("2".equals(flag)) {
            confirm.setText("发布");
            confirm.setBackgroundResource(R.drawable.bg_dateil);
            confirm.setTextColor(Color.parseColor("#ffffff"));
            cancel.setTextColor(Color.parseColor("#ffffff"));
            cancel.setText("存为草稿");
            stutasTv.setText("发布作品");
            contentTv.setText("是否发布录制的作品");
        } else if ("3".equals(flag)) {
            confirm.setText("确认");
            confirm.setBackgroundResource(R.drawable.bg_delete_confirm);
            confirm.setTextColor(Color.parseColor("#ff333436"));
            cancel.setTextColor(Color.parseColor("#ffffff"));
            cancel.setText("取消");
            stutasTv.setText("重新录制");
            contentTv.setText("是否重新录制");

        }
        recordStatusDialog = DialogPlus.newDialog(WorksDetailsAcitivity2.this)
                .setContentHolder(new ViewHolder(view))
                .setCancelable(false)
                .setGravity(Gravity.CENTER)
                .setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogPlus dialog) {

                    }
                }).create();
        recordStatusDialog.show();
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1;录制结束。2：是否发布作品.3:重新录制
                recordStatusDialog.dismiss();
                if ("2".equals(flag)) {//发布
                    sendData(1);
                    Intent intent = new Intent(constant.PERSONAL_MYRECEIVER);
                    sendBroadcast(intent);      //发送广播
                    playBtn.setImageResource(R.mipmap.ic_start_audiod);
                    playBtn.setEnabled(true);
                    //   upLoadingDialog();
                } else if ("3".equals(flag)) {//重新录制

                    //audioRecorder.setReset();
                    isDialogShow = true;
                    isRestart = true;
                    finishAndReset();
                    restarBtnLl.setVisibility(View.GONE);
                    stopRecorderLl.setVisibility(View.GONE);
                    bgmBtnLl.setVisibility(View.GONE);
                    playTv.setText("开始录音");
                    if (mediaPlayer != null) {
                        mediaPlayer.pause();//-----------------------//重置录音播放器
                    }
                    isAgain = true;
                    playBtn.setImageResource(R.mipmap.ic_start_audiod);
                    playBtn.setEnabled(true);
                    if (mIse.isEvaluating()) {
                        mIse.stopEvaluating();
                        isKeepTime = false;
                        progressBar.setProgress(0);
                    }

                } else if ("1".equals(flag)) {//录制结束
                    finishAndReset();
                    isDialogShow = true;
                    isAgain = true;
                    restarBtnLl.setVisibility(View.GONE);
                    bgmBtnLl.setVisibility(View.GONE);
                    stopRecorderLl.setVisibility(View.GONE);
                    if (mediaPlayer != null) {
                        mediaPlayer.pause();//-----------------------//重置录音播放器
                        isKeepTime = false;
                    }

                    // 解析最终结果
                    if (!TextUtils.isEmpty(mLastResult)) {
                        XmlResultParser resultParser = new XmlResultParser();
                        Result result = resultParser.parse(mLastResult);

                        if (null != result) {
                            // mResultEditText.setText(result.toString());
                            Log.d("result3333", result.toString() + "result11=" + result.total_score);
                            Log.d("result444444", "result11==" + result.total_score);
                            totalScore = result.total_score;
                        } else {
                            // showTip("解析结果为空");
                        }
                    }
                    if (mIse.isEvaluating()) {
                        mIse.stopEvaluating();
                        isKeepTime = false;
                        progressBar.setProgress(0);
                    }
                    playBtn.setImageResource(R.mipmap.ic_start_audiod);
                    //录制结束载分数未返回前显示加载界面,录音开始按钮和音乐选取按钮不可点击
                    playBtnLl.setEnabled(false);
                    bgmBtnLl.setEnabled(false);
                    //录制结束载分数未返回前显示加载界面
                    progressBarLl.setVisibility(View.VISIBLE);
                    progressBarLl.getBackground().setAlpha(125);
                    loadingTv.setText("分数计算中...");
                    // TODO: add setContentView(...) invocation
                    //  showScoreDialog();

                }

            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1;录制结束。2：是否发布作品.3:重新录制
                recordStatusDialog.dismiss();
                if ("2".equals(flag)) {
                    recordStatusDialog.dismiss();
                    sendData(0);
                    //存入草稿箱
                } else if ("3".equals(flag)) {
                    recordStatusDialog.dismiss();
                } else {
                    recordStatusDialog.dismiss();
                }
            }
        });
    }

    //得分弹框
    private void showScoreDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(WorksDetailsAcitivity2.this).inflate(R.layout.dialog_works_score2, null);
        Button confirm = view.findViewById(R.id.confir_btn);
        Button cancel = view.findViewById(R.id.cancel_btn);
        TextView stutasTv = view.findViewById(R.id.stutas_tv);
        TextView contentTv = view.findViewById(R.id.content_tv);
        TextView scoreTv = view.findViewById(R.id.score_tv);
        TextView score1 = view.findViewById(R.id.score1);
        TextView score2 = view.findViewById(R.id.score2);
        TextView score3 = view.findViewById(R.id.score3);
        TextView score4 = view.findViewById(R.id.score4);
        score1.setText(integrity_score + "分");
        score2.setText(phone_score + "分");
        score3.setText(tone_score + "分");
        score4.setText(fluency_score + "分");
        // scoreValue = Math.round((totalScore * 20));
        scoreValue = (int) Math.round((totalScore));
        if (scoreValue >= 80) {
            contentTv.setText("真棒，简直就是优秀本人!");
        } else if (scoreValue < 80 && scoreValue >= 70) {
            contentTv.setText("不错哦，争取再上一层楼!");
        } else if (scoreValue < 70 && scoreValue >= 60) {
            contentTv.setText("还需继续努力啊!");
        } else {
            contentTv.setText("分数较低!");
        }
        scoreTv.setText(scoreValue + "");
        builder.setView(view);
        builder.setCancelable(false);
        scoreDialog = builder.create();
        Log.d("dvgrg", "路过~~~~" + String.valueOf(Looper.getMainLooper() == Looper.myLooper()));
        scoreDialog.show();
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scoreDialog.dismiss();
                showDialog("2");
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scoreDialog.dismiss();
            }
        });
    }

    //取消/重选音乐弹框
    private void showMusicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(WorksDetailsAcitivity2.this).inflate(R.layout.dialog_works_music, null);
        Button confirm = view.findViewById(R.id.confir_btn);
        Button cancel = view.findViewById(R.id.cancel_btn);
        TextView musicName = view.findViewById(R.id.music_name);
        musicName.setText(musicStr);
        builder.setView(view);
        builder.setCancelable(true);
        musicDialog = builder.create();
        Log.d("dvgrg", "路过~~~~" + String.valueOf(Looper.getMainLooper() == Looper.myLooper()));
        musicDialog.show();
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //取消音乐
                musicId = -1;
                bgmTv.setText("未选择配乐");
                if (mediaPlayer != null) {
                    mediaPlayer.pause();//-----------------------//重置录音播放器
                }
                isThereMusic = false;
                musicDialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(WorksDetailsAcitivity2.this, BackgroundMusicActivity.class);
                startActivityForResult(intent, constant.WORKS_DETAIL_CODE);
                //过去重新选音乐时把朗读页面的音乐播放器停掉以免占用资源
                mediaPlayer.reset();
                mediaPlayer.seekTo(0);
                musicDialog.dismiss();

            }
        });
    }

    //上传进度弹框
    private void upLoadingDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(WorksDetailsAcitivity2.this).inflate(R.layout.dialog_up_loading, null);
        LinearLayout progressBar_ll = view.findViewById(R.id.progressBar_ll);
        progressBar_ll.getBackground().setAlpha(125);
        builder.setView(view);
        builder.setCancelable(false);
        upLoading = builder.create();
        upLoading.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Log.d("dvgrg", "路过~~~~" + String.valueOf(Looper.getMainLooper() == Looper.myLooper()));
        upLoading.show();
    }

    public void requestOver(Message msg) {
        switch (msg.what) {
            case HANDLER_CODE:
                //currentTime.setText("朗读已用时"+DateUtil.toVideoTime(time));
                Log.d("dgfdg", String.valueOf(time));//倒计时最后5秒钟，界面禁止滑动，倒计时结束后界面恢复初始化
                if ((1000 * 60 * 5 - time * 1000) <= 5000) {
                    isScroll = false;
                    aboutBeginLl.setVisibility(View.VISIBLE);
                    aboutBegin.setText(endCountDown + "");
                    aboutBegin.startAnimation(scaleAnimation);
                    aboutBegin.startAnimation(alphaAnimation);
                    playBtnLl.setEnabled(false);
                    restarBtnLl.setEnabled(false);
                    finishBtnLl.setEnabled(false);
                    if (5 == endCountDown) {
                        Log.d("endCountDown222", endCountDown + "");
                        finishAndReset();
                        isDialogShow = true;
                        isAgain = true;
                        restarBtnLl.setVisibility(View.GONE);
                        bgmBtnLl.setVisibility(View.VISIBLE);
                        stopRecorderLl.setVisibility(View.GONE);
                        isScroll = true;
                        playBtnLl.setEnabled(true);
                        restarBtnLl.setEnabled(true);
                        finishBtnLl.setEnabled(true);
                        aboutBeginLl.setVisibility(View.GONE);
                        endCountDown = 0;
                        if (mediaPlayer != null) {
                            mediaPlayer.pause();
                        }

                        if (mediaPlayer != null) {
                            mediaPlayer.pause();//-----------------------//重置录音播放器
                            isKeepTime = false;
                        }

                        // 解析最终结果
                        if (!TextUtils.isEmpty(mLastResult)) {
                            XmlResultParser resultParser = new XmlResultParser();
                            Result result = resultParser.parse(mLastResult);

                            if (null != result) {
                                // mResultEditText.setText(result.toString());
                                Log.d("result11", result.toString() + "result11=" + result.total_score);
                                Log.d("result222", "result11==" + result.total_score);
                                totalScore = result.total_score;
                            } else {
                                // showTip("解析结果为空");
                            }
                        }
                        if (mIse.isEvaluating()) {
                            mIse.stopEvaluating();
                            isKeepTime = false;
                            progressBar.setProgress(0);
                        }
                        playBtn.setImageResource(R.mipmap.ic_start_audiod);
                        //录制结束载分数未返回前显示加载界面,录音开始按钮和音乐选取按钮不可点击
                        playBtnLl.setEnabled(false);
                        bgmBtnLl.setEnabled(false);
                        //录制结束载分数未返回前显示加载界面
                        progressBarLl.setVisibility(View.VISIBLE);
                        progressBarLl.getBackground().setAlpha(125);
                        loadingTv.setText("分数计算中...");

                    }
                }
                Log.d("fdgsgsgs", time + "");
                currentTime.setText("朗读已用时：" + TimeUtil.formatLongToTimeStr(time));
                progressBar.setProgress(time);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        // audioRecorder.release();
        //audioRecorder.releaseAudioTrack();
        scheduledThreadPool.shutdown();
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        if (null != mIse) {
            mIse.destroy();
            mIse = null;
        }
    }

    //播放器播放
    public void onPlayerClick(String url) {
        Log.d("dsffff", "222223333" + url);
        Uri uri = Uri.parse(url);//网络中的音乐文件
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(this, uri);//音乐文件路径
            mediaPlayer.prepare();//资源文件准备
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (isAgain) {
            mediaPlayer.seekTo(0);
            isAgain = false;//非第一次录音，从头播放音乐
        }
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();//播放
        }
        // musicListAdapter.notifyDataSetChanged();
    }

    //播放器暂停
    public void onPauseClick() {
        Log.d("dsffff", "11111122222" + url);
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();//暂停
        }
        // musicListAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
       /* if (audioRecorder.getStatus() == AudioStatus.STATUS_START) {
            phoneToPause();
        }*/
    }

    //统计朗读/浏览次数
    private void putClickNum(int flag, int id) {
        NetWorkManager.getInstance().getNetWorkApiService().clickNum(flag, id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(WorksDetailsAcitivity2.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                    }
                });
    }

    /**
     * 获取文件MimeType
     *
     * @param filename 文件名
     * @return
     */
    private static String getMimeType(String filename) {
        FileNameMap filenameMap = URLConnection.getFileNameMap();
        String contentType = filenameMap.getContentTypeFor(filename);
        if (contentType == null) {
            contentType = "multipart/form-data"; //* exe,所有的可执行程序
        }
        return contentType;
    }

    //  只允许汉字
    public String stringFilter1(String str) throws PatternSyntaxException {
        //只允许汉字
        String regEx = "[a-zA-Z]";
       // String regEx = "[^\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        str.replaceAll("&nbsp;","");
        str.replaceAll("&amp;","");
        return m.replaceAll("").trim();
    }

    //  只允许英文
    public String stringFilter2(String str) throws PatternSyntaxException {
        //只允许汉字
        String regEx = "[^a-zA]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
    /**
     * @param htmlStr
     * @return 删除Html标签
     */
    private   String delHTMLTag(String htmlStr) {
        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 过滤html标签

        Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
        Matcher m_space = p_space.matcher(htmlStr);
       htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
        return htmlStr.trim(); // 返回文本字符串
    }
    class TimerTaskChildren extends TimerTask {
        private String flag;//1:开始动画倒计时6s;2:录音朗读倒计时10分钟

        public TimerTaskChildren(String flag) {
            this.flag = flag;
        }

        public String getFlag() {
            return flag;
        }

        public void setFlag(String flag) {
            this.flag = flag;
        }

        public void run() {
            Message msg = new Message();
            if ("1".equals(flag)) {
                countDown--;
                allCountDown--;
                msg.what = constant.WORKS_DETAIL_TIME;
                Bundle bundle = new Bundle();
                if (allCountDown < 3) {
                    bundle.putString("countDown", "开始");  //往Bundle中存放数据
                } else {
                    bundle.putString("countDown", countDown + "");  //往Bundle中存放数据
                }
                msg.setData(bundle);//mes利用Bundle传递数据
                mHandler.sendMessage(msg);
            } else {
                //录音倒计时
            }
        }
    }

}
